package com.dayaokeji.rhythmschoolstudent.client.mine.group;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.group.adapter.GroupMemberListAdapter;
import com.dayaokeji.rhythmschoolstudent.event.GroupEvent;
import com.dayaokeji.rhythmschoolstudent.event.UpdateGroupEvent;
import com.dayaokeji.rhythmschoolstudent.utils.DialogUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.rhythmschoolstudent.wiget.ConfirmDialog;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.GroupApi;
import com.dayaokeji.server_api.domain.DeleteGroup;
import com.dayaokeji.server_api.domain.Group;
import com.dayaokeji.server_api.domain.GroupMember;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;

/**
 * 群组成员信息
 */
public class GroupMembersActivity extends BaseActivity {

    public static final String EXTRA_GROUP_ENTITY = "group_entity";
    public static final String EXTRA_GROUP_ID = "group_id";
    public static final String EXTRA_GROUP_NAME = "group_name";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_groups)
    RecyclerView rvGroups;

    private Group group;

    private static final GroupApi groupApi = ApiUtils.getApi(GroupApi.class);
    private GroupMemberListAdapter groupMemberListAdapter;
    private Call<ServerResponse<List<GroupMember>>> memberListCall;
    private Call<ServerResponse<Void>> existGroupCall;
    private Call<ServerResponse<Void>> deleteCall;


    public static void navigation(Context context,Group group) {
        Intent intent = new Intent(context, GroupMembersActivity.class);
        intent.putExtra(EXTRA_GROUP_ENTITY, group);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_member_info);
        setSupportActionBar(toolbar);
        group = (Group) getIntent().getSerializableExtra(EXTRA_GROUP_ENTITY);
        init();
    }

    private void init() {
        setRecyclerView();
        requestGroupMembers();
    }

    private void setRecyclerView() {
        rvGroups.setLayoutManager(new LinearLayoutManager(this));
        rvGroups.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .sizeResId(R.dimen.default_divider_height)
                .colorResId(R.color.color_default_divider)
                .build());
        groupMemberListAdapter = new GroupMemberListAdapter();
        rvGroups.setAdapter(groupMemberListAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.group_member_info, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_del_group).setVisible(isMaster());
        menu.findItem(R.id.menu_exist_group).setVisible(!isMaster());
        return super.onPrepareOptionsMenu(menu);
    }

    private boolean isMaster() {
        if (UserUtils.getUserInfo() != null && !TextUtils.isEmpty(UserUtils.getUserInfo().getId())) {
            return group.getMaster() == Long.parseLong(UserUtils.getUserInfo().getId());
        }else{
            return false;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_exist_group:
                showExistGroupDialog();
                break;
            case R.id.menu_del_group:
                delExistGroupDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 退出群组对话框
     */
    private void showExistGroupDialog() {
        ConfirmDialog.ConfirmInfo confirmInfo = new ConfirmDialog.ConfirmInfo("退出群提示", "是否退出 <b><font color='#0074FE'>" +group.getName()+"</font></b> 群组？");
        ConfirmDialog confirmDialog = ConfirmDialog.Companion.newInstance(confirmInfo);
        confirmDialog.showNow(getSupportFragmentManager(), "exist_group");
        confirmDialog.setConfirmClickListener(new ConfirmDialog.ConfirmClickListener() {
            @Override
            public void click() {
                existGroup();
            }
        });
    }

    /**
     * 删除群组
     */
    private void delExistGroupDialog() {
        ConfirmDialog.ConfirmInfo confirmInfo = new ConfirmDialog.ConfirmInfo("删除群提示", "是否删除 <b><font color='#E20000'>" +group.getName()+"</font></b> 群组？");
        ConfirmDialog confirmDialog = ConfirmDialog.Companion.newInstance(confirmInfo);
        confirmDialog.showNow(getSupportFragmentManager(), "del_group");
        confirmDialog.setConfirmClickListener(new ConfirmDialog.ConfirmClickListener() {
            @Override
            public void click() {
                delGroup();
            }
        });
    }

    private void delGroup() {
        DeleteGroup deleteGroup = new DeleteGroup();
        deleteGroup.setGroupId(group.getId());
        deleteCall = groupApi.delete(deleteGroup);
        deleteCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("删除群组成功");
                    EventBus.getDefault().post(new GroupEvent(GroupEvent.Type.DELETE,group.getId()));
                    ActivityStackManager.finish();
                }
            }
        });
    }

    /**
     * 退出群组
     */
    private void existGroup() {
        HashMap<String,Object> params = new HashMap<>();
        params.put("id", group.getId());
        existGroupCall = groupApi.existGroup(params);
        existGroupCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("退群成功");
                    EventBus.getDefault().post(new GroupEvent(GroupEvent.Type.EXIST,group.getId()));
                    ActivityStackManager.finish();
                }
            }
        });
    }

    /**
     * 群组成员
     */
    private void requestGroupMembers() {
        memberListCall = groupApi.memberList(group.getId());
        memberListCall.enqueue(new ServerCallback<List<GroupMember>>(this, "正在加载数据...") {
            @Override
            public void onResponse(boolean success, ServerResponse<List<GroupMember>> response) {
                if (success) {
                    if (groupMemberListAdapter != null) {
                        groupMemberListAdapter.setNewData(response.getBody());
                        if (getSupportActionBar() != null) {
                            getSupportActionBar().setTitle("群组成员 (" + groupMemberListAdapter.getData().size() + ")");
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        if (existGroupCall != null) {
            existGroupCall.cancel();
        }
        if (memberListCall != null) {
            memberListCall.cancel();
        }
        if (deleteCall != null) {
            deleteCall.cancel();
        }
        super.onDestroy();
    }
}
